//
//  DataBase.m
//  Field_ijovo
//
//  Created by jiangxiaobai on 2017/2/24.
//  Copyright © 2017年 wly. All rights reserved.
//

#import "DataBase.h"

@implementation DataBase

static DataBase *_dataBase;
+ (instancetype)sharedDataBase{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _dataBase =[[DataBase alloc]init];
    });
    return _dataBase;
}

- (instancetype)init{
    self=[super init];
    if (self) {
        [self initDataBase];
    }
    return self;
}

- (void)initDataBase{
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 文件路径
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"model.sqlite"];
    // 实例化FMDataBase对象
    _queue = [FMDatabaseQueue databaseQueueWithPath:filePath];
    //创建用户表
    [self.queue inDatabase:^(FMDatabase *db) {
        // 初始化user表
        NSString *userSql = @"CREATE TABLE 'employees' ('id' INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL ,'employeeId' VARCHAR(255),'chineseName' VARCHAR(255),'avatar_thumb' VARCHAR(255),'mobilePhone' VARCHAR(255),'department' VARCHAR(255),'organization' VARCHAR(255),'isSelect' VARCHAR(255))";
        BOOL isOK= [db executeUpdate:userSql];
        if (isOK) {
            DLog(@"创建成功");
        }else{
            DLog(@"创建失败");
        }
    }];
    //创建组织表
    [self.queue inDatabase:^(FMDatabase *db) {
        // 初始化票据表
        NSString *organizationSql = @"CREATE TABLE 'Org' ('id' INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL ,'organizationId' VARCHAR(255),'organizationCount' VARCHAR(255),'parentId' VARCHAR(255),'isSelect' VARCHAR(255))";
        BOOL isOK= [db executeUpdate:organizationSql];
        if (isOK) {
            DLog(@"创建成功");
        }else{
            DLog(@"创建失败");
        }
    }];
    
    //创建群组表
    [self.queue inDatabase:^(FMDatabase *db) {
        // 初始化票据表
        NSString *organizationSql = @"CREATE TABLE 'groupChat' ('id' INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL ,'groupId' VARCHAR(255),'groupName' VARCHAR(255),'groupAvatar' VARCHAR(255))";
        BOOL isOK= [db executeUpdate:organizationSql];
        if (isOK) {
            DLog(@"创建成功");
        }else{
            DLog(@"创建失败");
        }
    }];
}

//// 判断是否存在表
//- (BOOL) isTableOK:(NSString *)tableName
//{
//    
//    FMResultSet *rs = [self.db executeQuery:@"select count(*) as 'count' from sqlite_master where type ='table' and name = ?", tableName];
//    while ([rs next])
//    {
//        // just print out what we've got in a number of formats.
//        NSInteger count = [rs intForColumn:@"count"];
//        
//        if (0 == count)
//        {
//            return NO;
//        }
//        else
//        {
//            return YES;
//        }
//    }
//    
//    return NO;
//}

@end
